<template>
  <view class="video">
    <!-- #ifdef H5 -->
    <swiper
      vertical
      acceleration
      :current="videoIndex"
      :style="{ width: width + 'px', height: height + 'px' }"
      @change="changeCurrent"
      @animationfinish="animationFinish"
      @transition="transition"
    >
      <swiper-item v-for="(item, index) in videoList" :key="index">
        <block v-if="Math.abs(videoIndex - index) <= 1">
          <view class="toggleVideo" @tap="handleClicked">
            <!-- 播放界面 -->
            <FindVideo
              ref="myVideo"
              :width="width"
              :height="height"
              :src="item.file"
              :play="item.play"
              :videoId="item.id"
              objectFit="contain"
              @pause="pauseVideo"
            />

            <!-- 组件 -->
            <view class="position-bottom-center" :style="{ bottom: `${safeBottom}` }">
              <view class="flex-direction align-end padding-lr-bj padding-bottom-sm flex justify-between">
                <view class="main-right align-center" @tap.stop.prevent>
                  <view class="main-right-user position-relative margin-bottom-xs align-center flex-direction-column">
                    <view @tap="handlePublishClick" class="main-right-image round align-center margin-bottom justify-center bg-white">
                      <image class="main-right-img round" src="/static/20250901230740.png" />
                    </view>
                    <view @tap="handleLiveClick" class="main-right-image round align-center margin-bottom justify-center bg-white">
                      <image class="main-right-img round" src="/static/20250901230810.png" />
                    </view>
                    <view @tap="handleStartLiveClick" class="main-right-image round align-center margin-bottom justify-center bg-white">
                      <image class="main-right-img round" src="/static/20250901230810.png" />
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </block>
      </swiper-item>
    </swiper>

    <!-- #endif -->
    <!-- #ifdef APP-NVUE -->

    <list
      @loadmore="loadData()"
      :loadmoreoffset="height * 3"
      :show-scrollbar="false"
      ref="listBox"
      :pagingEnabled="true"
      :scrollable="true"
      :style="{ width: width + 'px', height: height + 'px' }"
    >
      <cell v-for="(item, index) in videoList" :key="index" ref="item" class="item" :style="{ width: width + 'px', height: height + 'px' }">
        <view class="toggleVideo" @tap="handleClicked">
          <!-- 播放界面 -->
          <FindVideo
            ref="myVideo"
            :width="width"
            :height="height"
            :src="item.file"
            :play="item.play"
            :videoId="item.id"
            objectFit="contain"
            @pause="pauseVideo"
          />

          <!-- 底部右侧按钮，固定在右侧 -->
          <!-- 底部右侧按钮，固定在右侧 -->
          <!-- 底部右侧按钮，固定在右侧 -->
          <!-- 底部右侧按钮，固定在右侧 -->
          <!-- 底部右侧按钮，固定在右侧 -->
          <!-- style="{ bottom: `calc(${safeBottom})` }" -->
          <view class="position-bottom-center">
            <view class="flex-direction align-end padding-lr-bj padding-bottom-sm flex justify-between">
              <view class="main-right align-center" @tap.stop.prevent>
                <view class="main-right-user margin-bottom-xs align-center flex-direction-column">
                  <!-- v-if="config.is_video" -->

                  <view @tap="handlePublishClick" class="round align-center margin-bottom flex flex-col justify-center items-center bg-white">
                    <image class="main-right-img round main-right-image" src="/static/20250901230740.png" />
                    <!-- <text class="text-xs text-white">发布视频</text> -->
                  </view>
                  <view @tap="handleLiveClick" class="round align-center margin-bottom flex flex-col justify-center items-center bg-white">
                    <image class="main-right-img round main-right-image" src="/static/20250909235155.png" />
                    <!-- <text class="text-xs text-white">视频列表</text> -->
                  </view>
                  <!-- v-if="config.is_live" -->
                  <!-- / -->
                  <view @tap="handleStartLiveClick" class="round align-center margin-bottom flex flex-col justify-center items-center bg-white">
                    <image class="main-right-img round main-right-image" src="/static/20250901230810.png" />
                    <!-- <text class="text-xs text-white">开启直播</text> -->
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </cell>
    </list>
    <!-- #endif -->
  </view>
</template>

<script>
  import FindVideo from './find-video';
  import { baseUrl as BASE_URL } from '@/sheep/config/index.js';
  import sheep from '../../../sheep';

  let timer = null;
  export default {
    name: 'FindPlay',
    components: {
      FindVideo,
    },
    props: {
      height: {
        type: Number,
        default: 0,
      },
      width: {
        type: Number,
        default: 0,
      },
      bottom: {
        type: Number,
        default: 0,
      },
      safeBottom: {
        type: Number,
        default: 0,
      },
      isFocus: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        preload: 2, //当前页剩余个数换页
        clickNum: 0, //记录点击次数
        videoList: [],
        current_page: 1, //当前页码
        last_page: 1, //总页码
        status: 'loading',
        videoIndex: 0,
        oldVideoIndex: 0,
        commentData: {},
        providerList: [],
        config: {},
      };
    },
    mounted() {
      this.loadData();
      this.livePower();
    },
    methods: {
      livePower() {
        sheep.$api.yy.livePower().then((res) => {
          if (res.code === 1) {
            this.config = res.data;
          }
        });
      },
      // 保留原有的导航方法
      handleStartLiveClick() {
        uni.navigateTo({
          url: '/pages/video/live/live',
        });
      },
      handleLiveClick() {
        uni.navigateTo({
          url: '/pages/yy/videoLists',
        });
      },
      handlePublishClick() {
        uni.navigateTo({
          url: '/pages/yy/publishVideo',
        });
      },
      async loadData(type) {
        this.status = 'loading';

        if (type === 'update') {
          if (this.current_page >= this.last_page) {
            this.status = 'noMore';
            return false;
          } else {
            this.current_page += 1;
          }
        }

        // 	this.videoList = [
        // 		{
        // 			isLike:0,
        // 			isFollow:0,
        // 			id:11111,
        // 			initialTime:0,
        // 			content:'ddddddd',
        // 			video:{
        // 				fit:'contain',
        // 				duration:179,
        // 				cover_url:'https://video.scnxe.com/90ffe7f0e33771edbfbb6733a68f0102/snapshots/ee8c9aa160f44a55b1b8dd1c11b55bf6-00004.jpg',
        // 				url: 'https://mjy-1318105650.cos.ap-chengdu.myqcloud.com/uploads/20230519/8d4a3d36c63d04067ba71f97c0c8fcbf.mp4',
        // 			},
        // 			user:{
        // 				nickname:'222222',
        // 				id:1,
        // 				avatar:'https://video.scnxe.com/90ffe7f0e33771edbfbb6733a68f0102/snapshots/ee8c9aa160f44a55b1b8dd1c11b55bf6-00004.jpg',
        // 			},
        // 			play:false,
        // 		},

        // 		{
        // 			isLike:0,
        // 			isFollow:0,
        // 			id:22222,
        // 			initialTime:0,
        // 			content:'ddddddd',
        // 			video:{
        // 				fit:'contain',
        // 				duration:179,
        // 				cover_url:'https://video.scnxe.com/90ffe7f0e33771edbfbb6733a68f0102/snapshots/ee8c9aa160f44a55b1b8dd1c11b55bf6-00004.jpg',
        // 				url: 'http://video.scnxe.com/90ffe7f0e33771edbfbb6733a68f0102/54cede110da64f859ea194c5e0497330-ddfe38ca1354c99fba2072a6be750e69-ld.mp4',
        // 			},
        // 			user:{
        // 				nickname:'222222',
        // 				id:1,
        // 				avatar:'https://video.scnxe.com/90ffe7f0e33771edbfbb6733a68f0102/snapshots/ee8c9aa160f44a55b1b8dd1c11b55bf6-00004.jpg',
        // 			},
        // 			play:false,
        // 		}
        // 	];

        let that = this;
        let api = this.isFocus ? 'followlist' : 'videolist';

        let res = await sheep.$api.video[api]({
          page: this.current_page,
        });
        if (res.code === 1) {
          res.data.data.forEach(function (value, index) {
            value.play = false;
          });

          if (type === 'lower') {
            this.videoList = this.videoList.concat(res.data.data);
          } else {
            this.videoList = res.data.data;

            if (res.data.data.length > 0) {
              this.$nextTick(() => {
                this.videoPlay(this.videoIndex);
              });
            } else {
              uni.showToast({
                title: '系统还未上传任何视频！',
                icon: 'none',
              });
            }
          }

          this.current_page = res.data.current_page; //当前页码
          this.last_page = res.data.last_page; //总页码

          // 判断是否还有数据
          if (res.data.current_page === res.data.last_page || res.data.total === 0) {
            this.status = 'noMore';
          } else {
            this.status = 'more';
          }
        }

        // uni.request({
        // 	url: api,
        // 	data: {
        // 		page: this.current_page
        // 	},
        // 	success: res => {
        // 		res = res.res;
        // 		if (res.code === 1) {
        // 			res.data.data.forEach(function(value, index) {
        // 				value.play = false;
        // 			});

        // 			if (type === 'lower') {
        // 				this.videoList = this.videoList.concat(res.data.data);
        // 			} else {
        // 				this.videoList = res.data.data;

        // 				if (res.data.data.length > 0) {
        // 					this.$nextTick(() => {
        // 						this.videoPlay(this.videoIndex)
        // 					})

        // 				} else {
        // 					uni.showToast({
        // 						title: '系统还未上传任何视频！',
        // 						icon: 'none'
        // 					});
        // 				}
        // 			}

        // 			this.current_page = res.data.current_page; //当前页码
        // 			this.last_page = res.data.last_page; //总页码

        // 			// 判断是否还有数据
        // 			if (res.data.current_page === res.data.last_page || res.data.total === 0) {
        // 				this.status = 'noMore';
        // 			} else {
        // 				this.status = 'more';
        // 			}

        // 		} else {
        // 			uni.showToast({
        // 				title: res.data.msg,
        // 				icon: 'error'
        // 			});
        // 		}
        // 	}
        // });
      },
      async handleFollow(e) {
        // nvue 页面阻止事件冒泡
        // #ifdef APP-NVUE
        e.stopPropagation();
        // #endif

        var data = this.videoList[this.videoIndex];
        let res = await sheep.$api.video.follow({
          id: data.user_id,
        });
        if (res.code === 1) {
          data.is_follow = !data.is_follow;
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'error',
          });
        }

        // uni.request({
        // 	url: '/live/follow',
        // 	data:{
        // 		id: data.user_id,
        // 	},
        // 	success: res => {
        // 		res = res.res;
        // 		if(res.code===1){
        // 			data.is_follow = !data.is_follow;
        // 		}else{
        // 			uni.showToast({title: res.msg, icon: 'error'});
        // 		}
        // 	}
        // });
      },
      async handleLike(e) {
        // nvue 页面阻止事件冒泡
        // #ifdef APP-NVUE
        e.stopPropagation();
        // #endif

        let data = this.videoList[this.videoIndex];
        let res = await sheep.$api.video.videodz({
          id: data.id,
        });
        if (res.code === 1) {
          if (data.is_dz) {
            data.pv -= 1;
          } else {
            data.pv += 1;
          }

          data.is_dz = !data.is_dz;
        }
      },
      // 点击视频事件
      handleClicked() {
        console.log('go handleClicked');

        if (timer) {
          clearTimeout(timer);
        }

        this.clickNum++;
        timer = setTimeout(() => {
          if (this.clickNum >= 2) {
            this.handleLike();
          } else {
            this.videoList[this.videoIndex].play = !this.videoList[this.videoIndex].play;
          }
          this.clickNum = 0;
        }, 300);
      },
      // 播放当前视频
      videoPlay(index) {
        this.videoList[index].play = !this.videoList[index].play;
      },
      handleVideoPlay() {
        if (this.videoList.length > 0)
          this.$nextTick(() => {
            this.videoList[this.videoIndex].play = true;
          });
      },
      handleVideoPause() {
        for (let item of this.videoList) {
          item.play = false;
        }
      },
      // 时间打标
      pauseVideo(val) {},
      transition() {},
      animationFinish(e) {},
      changeCurrent(e) {
        // #ifdef H5
        this.videoIndex = e.detail.current;
        // #endif

        this.$nextTick(() => {
          for (let item of this.videoList) {
            item.play = false;
          }
          this.videoList[this.videoIndex].play = true;
        });
      },
      // 格式化html
      formatHtml(content) {
        return content.replace(/<\/?.+?>/g, '').replace(/ /g, '');
      },
      copy(content) {
        // 复制内容，必须字符串，数字需要转换为字符串
        content = typeof content === 'string' ? content : content.toString();

        //#ifndef H5
        uni.setClipboardData({
          data: content,
          success: function () {
            uni.showToast({
              title: `复制成功 ${content}`,
              icon: 'none',
            });
          },
          fail: function () {
            uni.showToast({
              title: `复制失败`,
              icon: 'none',
            });
          },
        });
        //#endif

        // #ifdef H5
        if (!document.queryCommandSupported('copy')) {
          //为了兼容有些浏览器 queryCommandSupported 的判断
          msg('浏览器不支持');
        }

        let textarea = document.createElement('textarea');
        textarea.value = content;
        textarea.readOnly = 'readOnly';
        document.body.appendChild(textarea);
        textarea.select(); // 选择对象
        textarea.setSelectionRange(0, content.length); //核心
        let result = document.execCommand('copy'); // 执行浏览器复制命令
        if (result) {
          uni.showToast({
            title: `复制成功 ${content}`,
            icon: 'none',
          });
        } else {
          uni.showToast({
            title: `复制失败`,
            icon: 'none',
          });
        }
        textarea.remove();
        // #endif
      },
    },
    watch: {
      // 加载新的视频
      videoIndex(newVal, oldVal) {
        if (this.videoList.length - this.videoIndex - 1 <= this.preload) {
          this.loadData('update');
        }

        this.oldVideoIndex = oldVal;
      },
    },
  };
</script>

<style>
  /deep/ .uni-swiper-slides {
    background-color: #000 !important;
  }
</style>

<style scoped>
  .share {
    border-top-left-radius: 26rpx;
    border-top-right-radius: 26rpx;
  }

  .share-scroll-view {
    /* #ifndef APP-PLUS */
    white-space: nowrap;
    /* #endif */
  }

  .share-scroll-view-item {
    /* #ifndef APP-PLUS */
    display: inline-flex;
    /* #endif */
    margin-right: 36rpx;
  }

  .share-scroll-view-item-button {
    background-color: rgba(0, 0, 0, 0);
    border: 0;
    padding: 0;
    flex-direction: column;
  }

  .share-scroll-view-item-button-icon {
    width: 100rpx;
    height: 100rpx;
    border-radius: 5000rpx;
  }

  /* #ifndef APP-PLUS */
  button:after {
    border: 0;
  }

  /* #endif */

  .video {
    background-color: #000;
  }

  .main-right {
    width: 98rpx;
  }

  .main-right-user {
    height: auto;
    width: 98rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    /* 确保在APP-NVUE环境中正确显示 */
    position: relative;
    z-index: 999;
  }

  .main-right-user-follow {
    bottom: 0;
    z-index: 999;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: row;
    position: absolute;
    width: 30rpx;
    height: 30rpx;
    background-color: #ff0000;
  }

  .main-right-image {
    width: 98rpx;
    height: 98rpx;
  }

  .main-right-img {
    width: 98rpx;
    height: 98rpx;
  }

  .goods {
    /* #ifndef APP-PLUS */
    white-space: nowrap;
    /* #endif */
    height: 174rpx;
  }

  .goods-item {
    /* #ifndef APP-PLUS */
    display: inline-block;
    /* #endif */
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 18rpx;
    margin-left: 14rpx;
    padding: 14rpx;
    height: 154rpx;
  }

  .goods-item-img {
    height: 126rpx;
    width: 126rpx;
    margin-right: 14rpx;
    border-radius: 4rpx;
  }

  .comment {
    background-color: rgba(10, 10, 10, 0.9);
    border-top: 2rpx solid rgba(255, 255, 255, 0.1);
    border-top-left-radius: 26rpx;
    border-top-right-radius: 26rpx;
  }

  .position-bottom-center {
    z-index: 999;
    position: absolute;
    bottom: 50px;
    right: 5px;
  }
  /* // */
  .padding-lr-bj {
    padding-left: 25rpx;
    padding-right: 25rpx;
  }

  .padding-bottom-sm {
    padding-bottom: 20rpx;
  }

  .flex-sub {
    flex: 1;
  }

  .padding-right-bj {
    padding-right: 25rpx;
  }

  .flex {
    display: flex;
  }

  .justify-between {
    justify-content: space-between;
  }

  .align-end {
    align-items: flex-end;
  }

  .align-center {
    align-items: center;
  }

  .text-white {
    color: #ffffff;
  }

  .left-describe {
    display: flex;
    flex-direction: row;
  }

  .text-white-8 {
    color: rgba(255, 255, 255, 0.8);
  }

  .text-lines-3 {
    lines: 3;
    text-overflow: ellipsis;
  }

  .focus-image {
    width: 50rpx;
    height: 50rpx;
  }

  .position-absolute {
    position: absolute;
  }

  .like-image {
    width: 50rpx;
    height: 50rpx;
  }

  .flex-direction {
    flex-direction: row;
  }

  .flex-direction-column {
    flex-direction: column;
  }

  .margin-bottom {
    margin-bottom: 20rpx;
  }

  .round {
    border-radius: 5000rpx;
  }

  .justify-center {
    justify-content: center;
  }

  .margin-top {
    margin-top: 30rpx;
  }

  .position-center {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
</style>
